<template>
    <div class="gaph">
        <select-category v-if="content" @handle="setCategoryID" :id="categoryID" />
    </div>
    <div class="gaph"><el-input v-model="title" style="100%" /></div>
    <div class="gaph" style="border: 1px solid #ccc">
        <editor @change="onChange" :content="content" />
    </div>
    <div class="gaph">
        <tag @handle="setTag" :content="valueText" />
    </div>
    <div>
        <el-button type="success" @click="add">更新</el-button>
    </div>
</template>

<script setup>
import { onBeforeUnmount, ref, onMounted } from 'vue'
import selectCategory from '@/components/selectCategory.vue'
import tag from '@/components/tag.vue'
import { post, get } from '@/util/request.js'
import router from '@/router'
import { useRoute } from 'vue-router'
import editor from '@/components/editor.vue'

const route = useRoute()
const queryParams = route.query

// 内容 HTML
const content = ref('')
const valueText = ref('')

// 添加文章的内容
const title = ref('')
const categoryID = ref(null)
const tags = ref([])

const props = defineProps({
    id: { type: Number }
})

const add = () => {
    let tagData = []
    tags.value.forEach((element) => {
        tagData.push({ title: element })
    })

    const data = {
        title: title.value,
        content: content.value,
        category_id: categoryID.value,
        tags: tagData,
        id: Number(queryParams.id)
    }
    post('/article/update', data).then((resp) => {
        router.push({ name: 'show-article' })
    })
}

const setCategoryID = (id) => {
    categoryID.value = id
}

const setTag = (v) => {
    tags.value = v
}

onMounted(() => {
    get('/article/find?id=' + queryParams.id).then((resp) => {
        title.value = resp.inst.title
        categoryID.value = resp.inst.category_id
        tags.value = resp.inst.tags
        content.value = resp.inst.content.length > 0 ? resp.inst.content : ' '
    })
})

// 富文本编辑器内容改变时
const onChange = (v) => {
    content.value = v
}
</script>
